export const createRoute = (record, location) => {
  let matched = []
  if(record) {
    while(record) {
      matched.unshift(record)
      record = record.parent
    }
  }
  return {
    ...location,
    matched
  }
}


const runQueue = (queue, iterator, complete) => {
  // let index = 0
  function next(index) {
    console.log(index, '????')
    if(index>=queue.length) {
      return complete()
    }
    let hook = queue[index]
    iterator(hook, ()=>{
      next(index+1)
    })
    
  }
  next(0)
}

export default class {
  constructor(router) {
    this.router = router

    this.current = createRoute(null, {
      path: '/'
    }) 
  }
  transitionTo(location, complete) {
    // 匹配 路径
    console.log(location)
    let current = this.router.match(location)
    if(this.current.path === location && this.current.matched.length == current.matched.length) {
      return
    }
    // 调用钩子
    let queue = this.router.beforeHooks
    console.log('钩子', queue)

    const iterator = (hook, next) => {
      hook(current, this.current, next)
    }
    

    runQueue(queue, iterator, ()=>{
      this.current = current; 
      this.cb && this.cb(current); 
      // current 变化更新 试图
  
      console.log('current', this.current)
      complete && complete()
    })


  }
  listen(cb) {
    this.cb = cb
  }
}